package org.dromara.crawler.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import org.bson.Document;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Shup
 * @date 2025/7/29 14:00
 */
public class DocConvertUtil {


    private static final ObjectMapper mapper = new ObjectMapper()
        .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

    public static <T> List<T> toEntityList(List<Document> docs, Class<T> clazz) {
        if (docs == null) {
            return Collections.emptyList();
        }
        return docs.stream().map(doc -> {
            // 先用 ObjectMapper 转实体
            T entity = mapper.convertValue(doc, clazz);
            // 如果 doc 里有 _id，尝试赋值到实体的 id
            Object idValue = doc.get("_id");
            if (idValue != null) {
                try {
                    // 反射获取 id 字段
                    Field idField = clazz.getDeclaredField("id");
                    idField.setAccessible(true);
                    idField.set(entity, idValue.toString());
                } catch (NoSuchFieldException e) {
                    // 没有 id 字段就忽略
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            return entity;
        }).collect(Collectors.toList());
    }

}
